package com.live.proxy.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.proxy.BaseActivity;
import com.live.proxy.R;
import com.live.proxy.model.ProxyModel;
import com.live.proxy.model.UserModel;
import com.live.proxy.sql.UserDatabase;
import com.live.proxy.tool.GetUtil;
import com.live.proxy.tool.OkHttpUtils;
import com.live.proxy.tool.StatusBarUtils;
import com.live.proxy.view.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class ProxyManageActivity extends BaseActivity {
    ImageButton proxy_manage_back;
    TextView proxy_manage_add;
    RecyclerView proxy_manage_recyclerview;

    UserDatabase userDb;
    UserModel userModel;
    List<ProxyModel> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_proxy_manage);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();

        proxy_manage_back = findViewById(R.id.proxy_manage_back);
        proxy_manage_add = findViewById(R.id.proxy_manage_add);
        proxy_manage_recyclerview = findViewById(R.id.proxy_manage_recyclerview);

        proxy_manage_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        proxy_manage_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_proxy_addproxy();
            }
        });
        init();
    }
    public void init(){
        try {
            JSONObject appJson = GetUtil.getAppInfo(getApplicationContext());
            getAccount(GetUtil.getProxyList(),appJson.toString(),userModel.getToken(),1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private MyAdapter adapter;

    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_proxy, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyAdapter.MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;

            mholder.item_proxy_user_account.setText(list.get(position).getUserAccount());
            mholder.item_proxy_create_time.setText(list.get(position).getCreateTime());
            mholder.item_proxy_user_nickname.setText(list.get(position).getUserNickname());
            mholder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog_proxy_giveinte(position);
                }
            });
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_proxy_create_time;
            TextView item_proxy_user_nickname;
            TextView item_proxy_user_account;

            public MyViewHolder(View itemView) {
                super(itemView);
                item_proxy_create_time = itemView.findViewById(R.id.item_proxy_create_time);
                item_proxy_user_nickname = itemView.findViewById(R.id.item_proxy_user_nickname);
                item_proxy_user_account = itemView.findViewById(R.id.item_proxy_user_account);
            }
        }
    }
    //新增代理
    public void dialog_proxy_addproxy(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_proxy_addproxy);
        final EditText dialog_addproxy_nickname = window.findViewById(R.id.dialog_addproxy_nickname);
        final EditText dialog_addproxy_account = window.findViewById(R.id.dialog_addproxy_account);
        final EditText dialog_addproxy_password = window.findViewById(R.id.dialog_addproxy_password);
        final EditText dialog_addproxy_intenum = window.findViewById(R.id.dialog_addproxy_intenum);
        final TextView dialog_addproxy_title = window.findViewById(R.id.dialog_addproxy_title);
        final TextView dialog_addproxy_no = window.findViewById(R.id.dialog_addproxy_no);
        final TextView dialog_addproxy_ok = window.findViewById(R.id.dialog_addproxy_ok);

        dialog_addproxy_title.setText("剩余["+userModel.getInteYue()+"]积分");

        dialog_addproxy_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_addproxy_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nickname = dialog_addproxy_nickname.getText().toString();
                String account = dialog_addproxy_account.getText().toString();
                String password = dialog_addproxy_password.getText().toString();
                String intenum = dialog_addproxy_intenum.getText().toString();

                if(nickname.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入昵称！",2);
                    return;
                }
                if(account.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入账号！",2);
                    return;
                }
                if(password.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入密码！",2);
                    return;
                }
                if(intenum.isEmpty() || Integer.valueOf(intenum) <= 0 || Integer.valueOf(intenum) > userModel.getInteYue()){
                    dialog_addproxy_title.setText("请输入下发积分不规范，需小于等于剩余["+userModel.getInteYue()+"]积分！");
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("nickname",nickname);
                    json.put("account",account);
                    json.put("password",password);
                    json.put("inte_num",intenum);
                    getAccount(GetUtil.addProxyUser(),json.toString(),userModel.getToken(),2);
                }catch (Exception e){
                    e.printStackTrace();
                }
                String proxyMsg = "代理昵称："+nickname+" \n账户："+account+" \n密码："+password+" \n充值积分："+intenum;
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("Label", proxyMsg);
                cm.setPrimaryClip(mClipData);
                ToastUtils.Setinfo(getApplicationContext(),"已复制到剪贴板",1);
                dialog.dismiss();
            }
        });
    }
    //下发积分
    public void dialog_proxy_giveinte(int position){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_proxy_giveinte);

        final EditText dialog_giveinte_num = window.findViewById(R.id.dialog_giveinte_num);
        final TextView dialog_giveinte_title = window.findViewById(R.id.dialog_giveinte_title);
        final TextView dialog_giveinte_no = window.findViewById(R.id.dialog_giveinte_no);
        final TextView dialog_giveinte_ok = window.findViewById(R.id.dialog_giveinte_ok);

        dialog_giveinte_title.setText("注意，\n 当前剩余["+userModel.getInteYue()+"]积分，\n下发对象为：【"+list.get(position).getUserNickname()+"】"+list.get(position).getUserAccount());

        dialog_giveinte_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_giveinte_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String intenum = dialog_giveinte_num.getText().toString();
                if(intenum.isEmpty() || Integer.valueOf(intenum) <= 0 || Integer.valueOf(intenum) > userModel.getInteYue()){
                    dialog_giveinte_title.setText("请输入下发积分不规范，需小于等于剩余["+userModel.getInteYue()+"]积分！");
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("uuid",list.get(position).getUuid());
                    json.put("inte_num",intenum);
                    getAccount(GetUtil.addProxyInte(),json.toString(),userModel.getToken(),3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    public static int REQUEST_STATUS = 0;
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastUtils.Setinfo(getApplicationContext(),msg.obj.toString(),2);
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            switch (REQUEST_STATUS){
                                case 1://获取列表
                                    if(list != null){
                                        list.clear();
                                    }else{
                                        list = new ArrayList<>();
                                    }
                                    JSONArray dataJson = json.getJSONArray("data");
                                    for (int i = 0 ; i < dataJson.length() ;i++){
                                        JSONObject inteJson = dataJson.getJSONObject(i);
                                        ProxyModel model = new ProxyModel();
                                        model.setUuid(inteJson.getInt("uuid"));
                                        model.setUserNickname(inteJson.getString("user_nickname"));
                                        model.setUserAccount(inteJson.getString("user_account"));
                                        model.setCreateTime(inteJson.getString("create_time"));
                                        list.add(model);
                                    }
                                    adapter = new MyAdapter();
                                    proxy_manage_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                                    proxy_manage_recyclerview.setAdapter(adapter);
                                    break;
                                case 2://新增代理
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    userModel.setInteYue(json.getInt("data"));
                                    userDb.updateInteYue(json.getInt("data"));
                                    init();
                                    break;
                                case 3://下发积分
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    userModel.setInteYue(json.getInt("data"));
                                    userDb.updateInteYue(json.getInt("data"));
                                    break;
                            }
                        }else{
                            ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),2);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr,String token,int STATUS){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                REQUEST_STATUS = STATUS;
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
}